package com.xwj.config;

import org.springframework.stereotype.Component;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by thinkjoy on 2017/7/26.
 */
@Component
public class SystemConfig {

    public String getIP() {
        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            List ip = new ArrayList();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) continue;
                Enumeration<InetAddress> addresss = ni.getInetAddresses();
                while (addresss.hasMoreElements()) {
                    InetAddress nextElement = addresss.nextElement();
                    if (nextElement.isLoopbackAddress()) continue;
                    String hostAddress = nextElement.getHostAddress();
                    if (hostAddress.indexOf(":") <= 0) {
                        ip.add(hostAddress);
                        break;
                    }
                }
            }
            if (ip.size() > 0) {
                return ip.get(0).toString();
            } else {
                return null;
            }
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }
}
